package com.jd.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jd.enums.CommentLevel;
import com.jd.enums.YesOrNo;
import com.jd.mapper.*;
import com.jd.pojo.*;
import com.jd.service.CarouselService;
import com.jd.service.ItemService;
import com.jd.utils.DesensitizationUtil;
import com.jd.utils.PagedGridResult;
import com.jd.vo.CommentLevelCountsVO;
import com.jd.vo.ItemCommentVO;
import com.jd.vo.SearchItemsVO;
import com.jd.vo.ShopcartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 商品业务层
 */
@Service
public class ItemServiceImpl implements ItemService{

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemsImgMapper itemsImgMapper;
    @Autowired
    private ItemsParamMapper itemsParamMapper;
    @Autowired
    private ItemsSpecMapper itemsSpecMapper;
    @Autowired
    private ItemsCommentsMapper itemsCommentsMapper;
    @Autowired
    private ItemCustomMapper itemCustomMapper;



    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Item queryItemById(String id) {
        return itemMapper.selectByPrimaryKey(id);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<ItemsImg> queryItemImgList(String itemId) {
        Example example=new Example(ItemsImg.class);
        Example.Criteria userCriteria = example.createCriteria();
        userCriteria.andEqualTo("itemId",itemId);
        return itemsImgMapper.selectByExample(example);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<ItemsSpec> queryItemSpecList(String itemId) {
        Example example=new Example(ItemsSpec.class);
        Example.Criteria userCriteria = example.createCriteria();
        userCriteria.andEqualTo("itemId",itemId);
        return itemsSpecMapper.selectByExample(example);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ItemsParam queryItemParam(String itemId) {
        Example example=new Example(ItemsParam.class);
        Example.Criteria userCriteria = example.createCriteria();
        userCriteria.andEqualTo("itemId",itemId);
        return itemsParamMapper.selectOneByExample(example);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public CommentLevelCountsVO queryCommentCount(String itemId) {
        Integer goodCounts=getCommentCounts(itemId,CommentLevel.GOOD.type);
        Integer normalCounts=getCommentCounts(itemId,CommentLevel.NORMAL.type);
        Integer badCounts=getCommentCounts(itemId,CommentLevel.BAD.type);
        Integer totalCounts=goodCounts+normalCounts+badCounts;

        CommentLevelCountsVO  commentLevelCountsVO=new CommentLevelCountsVO();
        commentLevelCountsVO.setTotalCounts(totalCounts);
        commentLevelCountsVO.setGoodCounts(goodCounts);
        commentLevelCountsVO.setBadCounts(badCounts);
        commentLevelCountsVO.setNormalCounts(normalCounts);
        return commentLevelCountsVO;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    Integer getCommentCounts(String itemId,Integer level){
        ItemsComments condion=new ItemsComments();
        condion.setItemId(itemId);
        if(level!=null){
            condion.setCommentLevel(level);
        }
       return itemsCommentsMapper.selectCount(condion);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PagedGridResult queryPageComments(String itemId,Integer level,
                                                                  Integer page,Integer pageSize){
        Map<String, Object> map = Maps.newHashMap();
        map.put("itemId", itemId);
        map.put("level", level);

        /**
         * page 第几页
         * pageSize 每页显示记录数
         */
        PageHelper.startPage(page,pageSize);
        List<ItemCommentVO> list=itemCustomMapper.queryItemComments(map);
        for(ItemCommentVO  item:list){
            item.setNickName(DesensitizationUtil.commonDisplay(item.getNickName()));
        }

        return setterPagedGrid(list,page);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PagedGridResult searchItems(String keywords, String sort, Integer page, Integer pageSize) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("keywords", keywords);
        map.put("sort", sort);
        /**
         * page 第几页
         * pageSize 每页显示记录数
         */
        PageHelper.startPage(page,pageSize);
        List<SearchItemsVO> list=itemCustomMapper.searchItems(map);
        return setterPagedGrid(list,page);
    }



    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PagedGridResult searchItems(Integer catId, String sort, Integer page, Integer pageSize) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("catId", catId);
        map.put("sort", sort);
        /**
        * page 第几页
         * pageSize 每页显示记录数
         */
        PageHelper.startPage(page,pageSize);
        List<SearchItemsVO> list=itemCustomMapper.searchItemsByThridCat(map);
        return setterPagedGrid(list,page);
    }


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<ShopcartVO> queryItemsBySpecIds(String specIds) {
        String ids[]=specIds.split(",");
        List<String> specIdsList= Lists.newArrayList();
        Collections.addAll(specIdsList,ids);
        return itemCustomMapper.queryItemsBySpecIds(specIdsList);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ItemsSpec queryItemSpecById(String specId) {
        return itemsSpecMapper.selectByPrimaryKey(specId);
    }


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public String queryItemMainImgById(String itemId) {
        ItemsImg itemsImg=new ItemsImg();
        itemsImg.setItemId(itemId);
        itemsImg.setIsMain(YesOrNo.YES.type);
        ItemsImg result=itemsImgMapper.selectOne(itemsImg);
        return result!=null?result.getUrl():"";
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void deceaseItemSpecStock(String specId, int buyCounts) {
        // 1、查询库存
//        int stock=10;
//        if(stock-buyCounts<0){
//            //提示用户库存不够
//        }
        //此种方式存在超卖的问题，共享资源数据的一致性
        /**
         * 1 synchronized 不推荐使用，集群下无用，性能低下
         * 2 锁数据库： 不推荐，导致数据库性能低下
         * 3 分布式锁  zookeeper redis
         */
        int result=itemCustomMapper.decreaseIitemSpecStock(specId,buyCounts);
        if(result!=1){
            throw new RuntimeException("订单创建失败，原因是库存不足");
        }
    }

    private  PagedGridResult setterPagedGrid(List<?> list, Integer page){
        PageInfo<?> pageList=new PageInfo<>(list);
        PagedGridResult grid=new PagedGridResult();
        grid.setPage(page);
        grid.setRows(list);
        grid.setTotal(pageList.getPages());
        grid.setRecords(pageList.getTotal());
        return grid;
    }
}




